package com.hqj.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.*;
import java.util.Random;

@Controller
public class IndexController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/getCodeImg")//获取验证码图片
    public void getCodeImg(HttpServletResponse resp)
            throws Exception{
        int width = 98,height = 34;
        //声明图片缓存对象
        BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2d画布
        Graphics2D g2d = bImage.createGraphics();
        //设置颜色
        g2d.setColor(Color.WHITE);
        //画一个实心矩形
        g2d.fillRect(0, 0, width, height);

        //g2d.setColor(Color.BLACK);
        //画一个空心的矩形
        //g2d.drawRect(0,0,width-1,height-1);

        //设置字体及大小
        Font f = new Font("Times New Roman",Font.BOLD,30);
        g2d.setFont(f);

        String code  = "";
        Random r = new Random();
        for(int i=0;i<4;i++){
            int a = r.nextInt(10)+0;
            code += a;
            //设置字体的颜色
            g2d.setColor(new Color(r.nextInt(110), r.nextInt(80), r.nextInt(60)));
            g2d.drawString(a+"", 23*i+16, 26);
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();

        //销毁验证码
        session.removeAttribute("loginCode");
        //把验证码存入session
        session.setAttribute("loginCode", code);

        //设置响应的参数
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/jpeg");
        //获取输出流对象
        ServletOutputStream sos = resp.getOutputStream();
        ImageIO.write(bImage, "jpeg", sos);
        //不可缺少，为了防止报错
        sos.close();

    }
}
